#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
"""
@File    :   install.py
@Time    :   2024-04-22 22:08
@Author  :   坐公交也用券
@Version :   1.0
@Contact :   faith01238@hotmail.com
@Homepage : https://liumou.site
@Desc    :   通过service的方式安装服务
"""
import os
import subprocess
from argparse import ArgumentParser
from sys import exit
import platform


def service_set(file="/root/.txy.env"):
	"""
	service set
	:param file: 设置环境变量文件
	:return:
	"""
	txt = f"""[Unit]
Description=This is a DDNS
After=network.target

[Service]
Type=simple
User=root
ExecStart=ddns
EnvironmentFile={file}
StandardOutput=journal
# 终止该服务所有进程
KillMode=control-group
Restart=on-failure
RestartPreventExitStatus=255
StandardError=inherit
SyslogIdentifier=com.liumou.ddns

[Install]
WantedBy=multi-user.target
Alias=com.liumou.ddns.service
"""
	return txt


class InstallDdns:
	def __init__(self):
		self.env_file = "/root/.txy.env"
		self.key = None
		self.id = None
		self.domain = None
		self.ip = None
		self.sub = None
		self.arch = None
		self.url = None
		self.bin = '/usr/bin/ddns'
		self.service_name = 'com.liumou.ddns.service'

	def set_info(self):
		if self.key is None:
			self.key = input('请输入key:\n').strip()
		if self.id is None:
			self.id = input('请输入id:\n').strip()
		if self.domain is None:
			self.domain = input('请输入域名,(默认liumou.site):\n').strip()
		if self.sub is None:
			self.sub = input('请输入子域名,例如www:\n')
		if self.domain == '':
			self.domain = 'liumou.site'
		if self.key == '':
			print('key不能为空')
			exit(1)
		if self.id == '':
			print('id不能为空')
			exit(1)

		if self.sub == '':
			print('子域名不能为空')
			exit(1)

	def get_env(self):
		"""
		获取环境变量
		:return:
		"""
		if platform.system().lower() != 'Linux'.lower():
			print('当前系统不支持')
			exit(2)
		arch_list = ['arm64', 'amd64', 'mips64', 'mips64le', 'arm', 'armv7l', 'x86_64']
		if platform.machine().lower() not in arch_list:
			print("当前架构不支持")
			exit(3)
		if platform.machine().lower() == 'armv7l':
			self.arch = 'arm'
		if platform.machine().lower() == 'mips64':
			self.arch = 'mips64le'
		if platform.machine().lower() == 'x86_64':
			self.arch = 'amd64'
		self.url = f'https://down.liumou.site/client/com.liumou.ddns-tencent/ddns_linux-{self.arch}.bin'

	def wget(self):
		"""
		下载ddns
		:return:
		"""
		os.system(f'rm -rf {self.bin}')
		if os.system(f'wget {self.url} -O {self.bin}') == 0:
			print('下载成功: ', self.url)
		else:
			print('下载失败:', self.url)
			exit(4)
		os.system(f'chmod +x {self.bin}')

	def service(self):
		"""
		设置service
		:return:
		"""
		s = subprocess.getstatusoutput(f"systemctl -all | grep {self.service_name}")
		if s[0] == 0:
			print('服务已存在')
			os.system(f"systemctl stop {self.service_name}")
			os.system(f"systemctl disable {self.service_name}")
			os.system(f"systemctl daemon-reload")
			os.system(f"rm -rf /etc/systemd/system/{self.service_name}")

		with open('/etc/systemd/system/com.liumou.ddns.service', 'w', encoding='utf-8') as f:
			f.write(service_set(file=self.env_file))
		os.system('systemctl daemon-reload')
		if os.system(f'systemctl enable {self.service_name}') == 0:
			print('服务设置成功')
		else:
			print('服务设置失败')
		exit(5)
		if os.system(f'systemctl start {self.service_name}') == 0:
			print('服务启动成功')
		else:
			print('服务启动失败')
			exit(6)
		print('服务已启动')

	def env(self):
		"""
		设置环境变量
		:return:
		"""
		txt = f"""TXY_ID={self.id}
TXY_KEY={self.key}
TXY_DOMAIN={self.domain}
TXY_SUBDOMIN={self.sub}
TXY_SUBDOMIN4={self.sub}
TXY_IP_TYPE=AAAA
TXY_REMARKE=OneClound
"""
		try:
			with open(self.env_file, 'w', encoding='utf-8') as f:
				f.write(txt)
			print('环境变量设置成功')
		except Exception as e:
			print('环境变量设置失败: ', e)

	def start(self):
		self.get_env()
		self.set_info()
		self.wget()
		self.env()
		self.service()
		print('开始安装')


if __name__ == '__main__':
	arg = ArgumentParser(description='通过service方式安装ddns服务', prog="ddns-install")
	arg.add_argument('--debug', action='store_true', help='Enable debug mode')
	h = '设置环境变量文件, 默认/root/.txy.env'
	arg.add_argument('-e', '--env', type=str, help=h, default='/root/.txy.env', required=False)
	h = '设置域名, 默认：liumou.site'
	arg.add_argument('-domain', '--domain', type=str, help=h, required=False, default='liumou.site')
	arg.add_argument('-sub', '--sub', type=str, help='设置子域名,例如：www(未传入则会进入手动输入)', required=False)
	arg.add_argument('-key', '--key', type=str, help='设置key(未传入则会进入手动输入)', required=False)
	arg.add_argument('-id', '--id', type=str, help='设置id(未传入则会进入手动输入), ', required=False)
	args = arg.parse_args()
	args_d = args.debug
	install = InstallDdns()
	install.id = args.id
	install.key = args.key
	install.domain = args.domain
	install.sub = args.sub
	install.start()
